# *-* coding: utf-8 *-*
from __future__ import absolute_import

from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QDialog
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QTableWidget
from PyQt4.QtGui import QTabWidget
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QMessageBox
from PyQt4.QtCore import Qt
from PyQt4.QtCore import SIGNAL

from ninja_ide.core import file_manager
from ninja_ide.tools import ui_tools


class PluginsManagerWidget(QDialog):

    def __init__(self, parent):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("Plugins Manager"))
        self.setModal(True)
        self.resize(700, 500)

        vbox = QVBoxLayout(self)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        self.overlay = ui_tools.Overlay(self)
        self.overlay.hide()

        self._available = []
        self._locals = []
        self._updates = []
        self._loading = True

#        self.thread = ThreadLoadPlugins(self)
#        self.connect(self.thread, SIGNAL("finished()"),
#            self.load_plugins_data)
#        self.connect(self.thread, SIGNAL("plugin_downloaded(PyQt_PyObject)"),
#            self._after_download_plugin)
#        self.thread.start()

    def _after_download_plugin(self, plugin):
#        self._installedWidget.add_table_items([plugin])
#        val = ninja_ide.core.load_installed_plugin(self._parent, plugin)
        val = False
        if val:
            QMessageBox.information(self, self.tr("GUI Plugins Installed"),
                self.tr("NINJA needs to be restarted for changes to take" \
                " effect.\nPlugin: ").arg(plugin[0]))
        pass

    def _load_plugins_data(self):
        if self._loading:
            self._updatesWidget = UpdatesWidget(self, self._updates)
            self._availableWidget = AvailableWidget(self, self._available)
            self._installedWidget = InstalledWidget(self, self._locals)
            self._tabs.addTab(self._updatesWidget, self.tr("Updates"))
            self._tabs.addTab(self._availableWidget,
                self.tr("Available Plugins"))
            self._tabs.addTab(self._installedWidget, self.tr("Installed"))
            self._loading = False
        self.overlay.hide()

    def download_plugins(self, plugs):
        self.overlay.show()
#        self.thread.plug = plugs
#        self.thread.runnable = self.thread.download_plugins_thread
#        self.thread.start()

    def mark_as_available(self, plug):
#        ninja_ide.core.uninstall_plugin(plug)
#        self.availableWidget.add_table_items([plug])
        pass

    def update_plugin(self, plugs):
        self.overlay.show()
#        self.thread.plug = plugs
#        self.thread.runnable = self.thread.update_plugin_thread
#        self.thread.start()

    def reset_installed_plugins(self):
#        local_plugins = ninja_ide.core.local_plugins()
#        local_plugins = [[k, local_plugins[k][0], local_plugins[k][1],
#            local_plugins[k][2]] for k in local_plugins]
#        self.installedWidget.reset_table(local_plugins)
        pass

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()


class UpdatesWidget(QWidget):

    def __init__(self, parent, updates):
        QWidget.__init__(self, parent)
        self._updates = updates
        vbox = QVBoxLayout(self)
        self._table = QTableWidget(1, 3)
        self._table.removeRow(0)
        vbox.addWidget(self._table)
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            updates)
        btnUpdate = QPushButton(self.tr("Update"))
        btnUpdate.setMaximumWidth(100)
        vbox.addWidget(btnUpdate)

        self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins)

    def _update_plugins(self):
        plugins = ui_tools.remove_get_selected_items(self._table)
        self.parent().update_plugin(plugins)


class AvailableWidget(QWidget):

    def __init__(self, parent, available):
        QWidget.__init__(self, parent)
        self._available = available
        vbox = QVBoxLayout(self)
        self._table = QTableWidget(1, 3)
        self._table.removeRow(0)
        vbox.addWidget(self._table)
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            available)
        btnInstall = QPushButton('Install')
        btnInstall.setMaximumWidth(100)
        vbox.addWidget(btnInstall)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(
            self.tr("Add an external Plugin. URL Zip File:")))
        self._link = QLineEdit()
        hbox.addWidget(self.link)
        btnAdd = QPushButton(self.tr("Add"))
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        lblExternalPlugin = QLabel(
            self.tr("(Write the URL of the Plugin and press 'Add')"))
        lblExternalPlugin.setAlignment(Qt.AlignRight)
        vbox.addWidget(lblExternalPlugin)

        self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins)
        self.connect(btnAdd, SIGNAL("clicked()"), self._install_external)

    def _install_plugins(self):
        plugins = ui_tools.remove_get_selected_items(self._table)
        self.parent().download_plugins(plugins)

    def _install_external(self):
        if self._link.text().isEmpty():
            QMessageBox.information(self, self.tr("External Plugins"),
                self.tr("URL from Plugin missing..."))
            return
        plug = [
            file_manager.get_module_name(str(self._link.text())),
            'External Plugin',
            '1.0',
            str(self._link.text())]
        self.parent().download_plugins(plug)
        self._link.setText('')

    def add_table_items(self, plugs):
        self._available += plugs
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            self._available)


class InstalledWidget(QWidget):

    def __init__(self, parent, installed):
        QWidget.__init__(self, parent)
        self._installed = installed
        vbox = QVBoxLayout(self)
        self._table = QTableWidget(1, 3)
        self._table.removeRow(0)
        vbox.addWidget(self._table)
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            self._installed)
        btnUninstall = QPushButton(self.tr("Uninstall"))
        btnUninstall.setMaximumWidth(100)
        vbox.addWidget(btnUninstall)

        self.connect(btnUninstall, SIGNAL("clicked()"),
            self._uninstall_plugins)

    def add_table_items(self, plugs):
        self._installed += plugs
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            self._installed)

    def _uninstall_plugins(self):
        ui_tools.remove_get_selected_items(self._table)

    def reset_table(self, installed):
        self._installed = installed
        while self._table.rowCount() > 0:
            self._table.removeRow(0)
        ui_tools.load_table(self._table, ['Name', 'Version', 'Description'],
            self._installed)
